import matplotlib.pyplot as plt
import numpy as np

#中文
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def demonstrate_tangent_line():
    """演示导数的几何意义：切线斜率"""
    # 定义函数和点
    f = lambda x: np.sin(x) + 0.1*x**2
    x0 = 1.5
    derivative_at_x0 = np.cos(x0) + 0.2*x0  # f'(x) = cos(x) + 0.2x
    
    x = np.linspace(0, 3, 1000)
    y = f(x)
    
    plt.figure(figsize=(12, 5))
    
    # 主图：函数曲线和切线
    plt.subplot(1, 2, 1)
    plt.plot(x, y, 'b-', linewidth=2, label='f(x) = sin(x) + 0.1x²')
    plt.scatter([x0], [f(x0)], color='red', s=100, zorder=5)
    
    # 切线
    tangent_line = f(x0) + derivative_at_x0 * (x - x0)
    plt.plot(x, tangent_line, 'r--', linewidth=2, 
             label=f'切线: 斜率 = {derivative_at_x0:.3f}')
    
    # 割线（不同Δx值）
    for dx in [1.0, 0.5, 0.2]:
        x1 = x0 + dx
        slope_secent = (f(x1) - f(x0)) / (x1 - x0)
        secent_line = f(x0) + slope_secent * (x - x0)
        plt.plot(x, secent_line, ':', alpha=0.7, 
                 label=f'割线(Δx={dx}): 斜率 = {slope_secent:.3f}')
    
    plt.title('从割线到切线的演变过程')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    # 局部放大图
    plt.subplot(1, 2, 2)
    x_zoom = np.linspace(x0-0.5, x0+0.5, 200)
    y_zoom = f(x_zoom)
    tangent_zoom = f(x0) + derivative_at_x0 * (x_zoom - x0)
    
    plt.plot(x_zoom, y_zoom, 'b-', linewidth=2, label='f(x)')
    plt.plot(x_zoom, tangent_zoom, 'r--', linewidth=2, label='切线')
    
    # 标记点和斜率
    plt.scatter([x0], [f(x0)], color='red', s=100, zorder=5)
    plt.annotate(f'点P({x0:.1f}, {f(x0):.2f})', 
                (x0, f(x0)), xytext=(x0+0.1, f(x0)-0.2))
    
    plt.title('切线斜率的局部放大图')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.show()

demonstrate_tangent_line()